<?php
namespace app\index\controller;

use app\BaseController;
use support\Response;
use sword\Cache\Facade\Cache;
use think\facade\Db;

//#[MiddlewareAttr(AuthMiddleware::class)]
class Test extends BaseController
{

    public function test(): Response
    {
//        $info = Cache::set('test', 'test1');
//        $info = Cache::get('test');
        $info = Cache::remember('test', function (){
            return 'test44';
        }, 10);

        return $this->withData(0, 'success', $info);
    }

    /**
     * 获取数据表字段生成模型ide注解
     * @return string
     * @api /index/test/fields?name=role
     */
    public function fields(): string
    {
        $table = request()->get('name', 'user');
        $fields = Db::getFields($table);

        //查询表备注
        try{
            $tableComment = Db::query("SELECT TABLE_COMMENT FROM information_schema.TABLES WHERE table_name = '{$table}'");
            if ($tableComment){
                $tableComment = " * {$tableComment[0]['TABLE_COMMENT']}\n";
            }
        }catch (\Exception $e){
            $tableComment = '';
        }

        $res = "/**\n$tableComment";

        foreach ($fields as $v){
            $type = $v['type'];
            $comment = $v['comment'];
            $type = str_replace(' unsigned', '', $type);

            //数据类型转换
            $type = match ($type) {
                "smallint", "int", "bigint", "tinyint" => 'int',
                "decimal" => 'double',
                default => 'string',
            };

            $res .= " * @property $type \${$v['name']} {$comment}\n";
        }
        $res .= "*/";

        return $res;
    }

}
